# coding:utf-8
from django import forms
from django.core.validators import ValidationError
from web.forms.bootstrap import BootstrapForm
from web import models
from .widgets import ColorRadioSelect


class ProjectModelForm(BootstrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea(),
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data['name']
        # 1.检验该用户是否存在同名项目
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('该项目名已存在')
        # 2.检验当前用户是否还有额度创建项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('创建项目数量已达上限，增加创建项目数量请购买VIP')
        return name
